<template>

  <div>
    <el-checkbox :indeterminate="isIndeterminate" style="padding-right:10px;" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
    <el-checkbox-group v-model="roles" style="display:inline;" @change="handleCheckedRolesChange">
      <el-tooltip :open-delay="500" :content="role.description" :key="role.id" v-for="role in allRoles" placement="top">
        <el-checkbox  style="margin-left:0;padding-right:10px;" :label="role.id">{{role.name}}</el-checkbox>
      </el-tooltip>
    </el-checkbox-group>
  </div>

</template>


<script>

import axios from "@/util/axios";
import {isInArr,arrIsInArr,arrUnique} from "@/util/arr";

let allRoleIds = [];
let ldPromise = null;

export default {

  props:['value','url'],

  mounted(){
    ldPromise = this.load();
  },

  watch:{

    value(newVal){
      ldPromise.then(() => {
        const {ctn,nctn} = arrIsInArr(newVal,allRoleIds);
        this.roles = ctn;
        if(nctn.length > 0 ){
          this.$emit('not-contain',nctn);
        }
        this.checkIndeterminate();
      });
    }

  },

  data(){
    return {
      roles:[],
      allRoles:[],
      checkAll: false,
      isIndeterminate: false
    }
  },

  methods:{

    load(){
      return new Promise((resolve,reject) => {
        allRoleIds = [];
        axios.get(this.url).then(({data}) => {
          this.allRoles = data;
          for (const {id} of data) {
            allRoleIds.push(id);
          }
          resolve();
        }).catch(reject);
      });
    },

    handleCheckAllChange(va) {
      this.roles = va ? allRoleIds : [];
      this.$emit('input',this.roles);
      this.isIndeterminate = false;
    },

    checkIndeterminate(){
      const cnt = this.roles.length,ttl = allRoleIds.length;
      this.isIndeterminate = (cnt > 0) && (cnt < ttl);
      this.checkAll = cnt === ttl;
    },

    handleCheckedRolesChange(value) {
      let checkedCount = value.length;
      this.$emit('input',this.roles);
      this.checkAll = checkedCount === this.allRoles.length;
    }

  }


}

</script>
